<template>
  <div class="batch-container">
    <a-spin :loading="loading">
      <!-- 上传区域 -->
      <a-card title="批量创建用户" class="upload-card">
        <a-upload
          accept=".xls,.xlsx"
          :show-file-list="false"
          :auto-upload="false"
          @change="handleChange"
        >
          <template #upload-button>
            <a-button type="primary" :disabled="loading">
              <template #icon>
                <icon-upload />
              </template>
              选择Excel文件
            </a-button>
          </template>
        </a-upload>

        <div class="file-requirements">
          <p>文件要求：</p>
          <ul>
            <li>文件格式：.xls 或 .xlsx</li>
            <li>列顺序：姓名 → 账号 → 密码</li>
            <li>
              模板下载：<a-link @click="handleExcelDownload"
                >批量创建用户模板.xlsx</a-link
              >
            </li>
          </ul>
        </div>
      </a-card>

      <!-- 结果展示 -->
      <a-card v-if="resultData" class="result-card">
        <!-- 统计信息 -->
        <a-space :size="30">
          <a-card>
            <a-statistic
              title="总记录数"
              :value="resultData.totalCount"
              :precision="0"
            />
          </a-card>
          <a-card>
            <a-statistic
              title="成功数量"
              :value="resultData.successCount"
              :precision="0"
              value-style="color: #00B42A;"
            />
          </a-card>
          <a-card>
            <a-statistic
              title="失败数量"
              :value="resultData.totalCount - resultData.successCount"
              :precision="0"
              value-style="color: #F53F3F;"
            />
          </a-card>
        </a-space>

        <!-- 失败记录表格 -->
        <div v-if="resultData.failedRecords?.length" class="failed-table">
          <a-typography-title :heading="6">失败记录</a-typography-title>
          <a-table
            :columns="failedColumns"
            :data="resultData.failedRecords"
            row-key="rowNumber"
            :pagination="{ pageSize: 5 }"
            bordered
            size="small"
          >
            <template #errorMessage="{ record }">
              <span style="color: #f53f3f">{{ record.errorMessage }}</span>
            </template>
          </a-table>
        </div>
      </a-card>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Message } from "@arco-design/web-vue";
import { UserControllerService } from "../../../generated";
import { IconUpload } from "@arco-design/web-vue/es/icon";

const loading = ref(false);
const resultData = ref(null);

// 表格列配置
const failedColumns = [
  { title: "行号", dataIndex: "rowNumber", width: 100 },
  { title: "错误原因", slotName: "errorMessage" },
];

// 处理文件上传
const handleChange = async (files: any, currentFile: any) => {
  if (!currentFile) return;

  loading.value = true;
  resultData.value = null; // 重置结果

  try {
    const formData = new FormData();
    formData.append("file", currentFile.file);

    const response = await UserControllerService.batchRegisterUsingPost(
      formData
    );

    if (response.code === 0) {
      resultData.value = response.data;
      Message.success(`上传完成，成功${response.data.successCount}条`);
    } else {
      Message.error(`上传失败: ${response.message}`);
    }
  } catch (error) {
    Message.error(`上传失败: ${error.message || "服务器错误"}`);
  } finally {
    loading.value = false;
  }
};

// 模板文件下载
const handleExcelDownload = async () => {
  try {
    const response = await fetch("/template.xlsx");
    if (!response.ok) {
      throw new Error("模板文件下载失败");
    }
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "批量创建用户模板.xlsx";
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
  } catch (error) {
    Message.error("模板文件下载失败：" + (error.message || "未知错误"));
  }
};
</script>

<style scoped>
.batch-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.upload-card {
  margin-bottom: 20px;
}

.file-requirements {
  margin-top: 16px;
  color: #86909c;
}

.file-requirements ul {
  padding-left: 20px;
  margin: 8px 0;
}

.result-card {
  margin-top: 20px;
}

.failed-table {
  margin-top: 20px;
}

:deep(.arco-table-cell) {
  word-break: break-word;
}
</style>
